#coding=utf-8
#Boa:Frame:FramePurOrder

import wx
import wx.grid

import DlgPopupSupplier
import DlgSelectPro
import DlgProGX

from product import *
from ctrlAider import *
from MyListCtrl import *
from config import *
import kit


def create(parent):
    return FramePurOrder(parent)

[wxID_FRAMEPURORDER, wxID_FRAMEPURORDERBTNCANCEL, 
 wxID_FRAMEPURORDERBTNHISTORY, wxID_FRAMEPURORDERBTNSAVE, 
 wxID_FRAMEPURORDERBTNSHOWCUSTOMER, wxID_FRAMEPURORDERCOMBOBOX_STAFF, 
 wxID_FRAMEPURORDERDATESO, wxID_FRAMEPURORDERGRIDSOPROLIST, 
 wxID_FRAMEPURORDERSTATICBOX1, wxID_FRAMEPURORDERSTATICBOX_HISTORY, 
 wxID_FRAMEPURORDERSTATICTEXT1, wxID_FRAMEPURORDERSTATICTEXT2, 
 wxID_FRAMEPURORDERSTATICTEXT3, wxID_FRAMEPURORDERSTATICTEXT4, 
 wxID_FRAMEPURORDERSTATICTEXT_CUST, wxID_FRAMEPURORDERSTATICTEXT_DATE, 
 wxID_FRAMEPURORDERSTATICTEXT_MEMO, wxID_FRAMEPURORDERSTATICTEXT_SHISHOU, 
 wxID_FRAMEPURORDERSTATICTEXT_SOID, wxID_FRAMEPURORDERSTATICTEXT_STAFF, 
 wxID_FRAMEPURORDERSTATICTEXT_YINGSHOU, wxID_FRAMEPURORDERSTATICTEXT_YOUHUI, 
 wxID_FRAMEPURORDERTCCUSTOMER, wxID_FRAMEPURORDERTCMEMO, 
 wxID_FRAMEPURORDERTCPAID, wxID_FRAMEPURORDERTCSHISHOU, 
 wxID_FRAMEPURORDERTCTOTAL, wxID_FRAMEPURORDERTCUNPAID, 
 wxID_FRAMEPURORDERTCYINGSHOU, wxID_FRAMEPURORDERTCYOUHUI, 
 wxID_FRAMEPURORDERTSOID, 
] = [wx.NewId() for _init_ctrls in range(31)]

class FramePurOrder(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAMEPURORDER, name=u'FramePurOrder',
              parent=prnt, pos=wx.Point(0, 145), size=wx.Size(1288, 652),
              style=wx.DEFAULT_FRAME_STYLE, title=u'\u91c7\u8d2d\u8ba2\u5355')
        self.SetClientSize(wx.Size(1280, 618))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.staticText_SOID = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_SOID,
              label=u'\u5355\u53f7\uff1a', name=u'staticText_SOID', parent=self,
              pos=wx.Point(408, 48), size=wx.Size(64, 14), style=0)
        self.staticText_SOID.SetForegroundColour(wx.Colour(255, 0, 0))

        self.staticText_date = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_DATE,
              label=u'\u65e5\u671f\uff1a', name=u'staticText_date', parent=self,
              pos=wx.Point(408, 96), size=wx.Size(56, 14), style=0)

        self.dateSO = wx.DatePickerCtrl(id=wxID_FRAMEPURORDERDATESO,
              name=u'dateSO', parent=self, pos=wx.Point(472, 88),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateSO.SetLabel(u'2013-11-27')
        self.dateSO.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateSO.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateSO.Bind(wx.EVT_DATE_CHANGED, self.OnDateChanged,
              id=wxID_FRAMEPURORDERDATESO)

        self.staticText_cust = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_CUST,
              label=u'\u4f9b\u8d27\u5546\uff1a', name=u'staticText_cust',
              parent=self, pos=wx.Point(72, 88), size=wx.Size(68, 16), style=0)

        self.staticText_YingShou = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_YINGSHOU,
              label=u'\u5e94\u4ed8\u91d1\u989d\uff1a',
              name=u'staticText_YingShou', parent=self, pos=wx.Point(72, 440),
              size=wx.Size(85, 16), style=0)

        self.tcYingShou = wx.TextCtrl(id=wxID_FRAMEPURORDERTCYINGSHOU,
              name=u'tcYingShou', parent=self, pos=wx.Point(160, 440),
              size=wx.Size(80, 22), style=0, value=u'0.0')
        self.tcYingShou.SetEditable(False)
        self.tcYingShou.Enable(False)

        self.staticText_shishou = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_SHISHOU,
              label=u'\u5b9e\u4ed8\u91d1\u989d\uff1a',
              name=u'staticText_shishou', parent=self, pos=wx.Point(272, 440),
              size=wx.Size(85, 16), style=0)

        self.tcShiShou = wx.TextCtrl(id=wxID_FRAMEPURORDERTCSHISHOU,
              name=u'tcShiShou', parent=self, pos=wx.Point(368, 440),
              size=wx.Size(84, 22), style=0, value=u'0.0')
        self.tcShiShou.SetEditable(False)
        self.tcShiShou.Enable(False)

        self.staticText_YouHui = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_YOUHUI,
              label=u'\u4f18\u60e0\u91d1\u989d\uff1a',
              name=u'staticText_YouHui', parent=self, pos=wx.Point(456, 440),
              size=wx.Size(85, 16), style=0)

        self.tcYouHui = wx.TextCtrl(id=wxID_FRAMEPURORDERTCYOUHUI,
              name=u'tcYouHui', parent=self, pos=wx.Point(544, 440),
              size=wx.Size(88, 22), style=0, value=u'0.0')
        self.tcYouHui.SetEditable(True)
        self.tcYouHui.Enable(True)

        self.staticText_staff = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_STAFF,
              label=u'\u7ecf\u624b\u4eba\uff1a', name=u'staticText_staff',
              parent=self, pos=wx.Point(72, 480), size=wx.Size(72, 14),
              style=0)

        self.comboBox_staff = wx.ComboBox(choices=[],
              id=wxID_FRAMEPURORDERCOMBOBOX_STAFF, name=u'comboBox_staff',
              parent=self, pos=wx.Point(160, 480), size=wx.Size(146, 24),
              style=0, value=u'')
        self.comboBox_staff.SetLabel(u'')

        self.staticText_memo = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT_MEMO,
              label=u'\u5907\u6ce8\uff1a', name=u'staticText_memo', parent=self,
              pos=wx.Point(72, 520), size=wx.Size(72, 14), style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_FRAMEPURORDERTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(160, 520), size=wx.Size(264, 72),
              style=wx.TE_MULTILINE, value=u'')

        self.gridSOProList = wx.grid.Grid(id=wxID_FRAMEPURORDERGRIDSOPROLIST,
              name=u'gridSOProList', parent=self, pos=wx.Point(64, 144),
              size=wx.Size(552, 224), style=wx.STATIC_BORDER)
        self.gridSOProList.SetHelpText(u'')
        self.gridSOProList.SetLabel(u'gridSOProList')
        self.gridSOProList.SetToolTipString(u'gridSOProList')
        self.gridSOProList.SetWindowVariant(wx.WINDOW_VARIANT_LARGE)
        self.gridSOProList.SetColLabelSize(32)
        self.gridSOProList.SetRowLabelSize(20)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_CHANGE,
              self.OnGridSOProListGridCellChange)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_SELECT_CELL,
              self.OnGridSOProListGridSelectCell)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,
              self.OnGridSOProListGridCellRightClick)

        self.staticBox_history = wx.StaticBox(id=wxID_FRAMEPURORDERSTATICBOX_HISTORY,
              label=u'\u6d88\u8d39\u8bb0\u5f55', name=u'staticBox_history',
              parent=self, pos=wx.Point(736, 48), size=wx.Size(448, 512),
              style=0)

        self.TSOID = wx.StaticText(id=wxID_FRAMEPURORDERTSOID,
              label=u'XS-2014-03-07-0001', name=u'TSOID', parent=self,
              pos=wx.Point(472, 48), size=wx.Size(162, 16), style=0)
        self.TSOID.SetForegroundColour(wx.Colour(255, 0, 0))

        self.btnHistory = wx.Button(id=wxID_FRAMEPURORDERBTNHISTORY,
              label=u'\u5f80\u6765\u5355\u636e', name=u'btnHistory',
              parent=self, pos=wx.Point(760, 80), size=wx.Size(88, 26),
              style=0)
        self.btnHistory.Bind(wx.EVT_BUTTON, self.OnBtnHistoryButton,
              id=wxID_FRAMEPURORDERBTNHISTORY)

        self.btnSave = wx.Button(id=wxID_FRAMEPURORDERBTNSAVE,
              label=u'\u4fdd\u5b58\u8ba2\u5355', name=u'btnSave', parent=self,
              pos=wx.Point(496, 480), size=wx.Size(93, 26), style=0)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnBtnSaveButton,
              id=wxID_FRAMEPURORDERBTNSAVE)

        self.btnCancel = wx.Button(id=wxID_FRAMEPURORDERBTNCANCEL,
              label=u'\u9000\u51fa', name=u'btnCancel', parent=self,
              pos=wx.Point(496, 560), size=wx.Size(93, 26), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_FRAMEPURORDERBTNCANCEL)

        self.btnShowCustomer = wx.Button(id=wxID_FRAMEPURORDERBTNSHOWCUSTOMER,
              label=u'+', name=u'btnShowCustomer', parent=self,
              pos=wx.Point(328, 88), size=wx.Size(32, 26), style=0)
        self.btnShowCustomer.Bind(wx.EVT_BUTTON, self.OnBtnShowCustomerButton,
              id=wxID_FRAMEPURORDERBTNSHOWCUSTOMER)

        self.TCCustomer = wx.TextCtrl(id=wxID_FRAMEPURORDERTCCUSTOMER,
              name=u'TCCustomer', parent=self, pos=wx.Point(136, 88),
              size=wx.Size(184, 26), style=0, value=u'')

        self.staticText1 = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT1,
              label=u'\u5546\u54c1\u5165\u5e93', name='staticText1',
              parent=self, pos=wx.Point(240, 32), size=wx.Size(84, 20),
              style=0)
        self.staticText1.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, u'\u6977\u4f53_GB2312'))

        self.staticBox1 = wx.StaticBox(id=wxID_FRAMEPURORDERSTATICBOX1,
              label=u'', name='staticBox1', parent=self, pos=wx.Point(64, 72),
              size=wx.Size(552, 56), style=0)
        self.staticBox1.SetBackgroundColour(wx.Colour(200, 208, 253))

        self.staticText2 = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT2,
              label=u'\u5e94\u6536\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(760, 120), size=wx.Size(85, 16),
              style=0)

        self.staticText3 = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT3,
              label=u'\u5df2\u6536\u91d1\u989d\uff1a', name='staticText3',
              parent=self, pos=wx.Point(760, 144), size=wx.Size(85, 16),
              style=0)

        self.staticText4 = wx.StaticText(id=wxID_FRAMEPURORDERSTATICTEXT4,
              label=u'\u672a\u6536\u91d1\u989d\uff1a', name='staticText4',
              parent=self, pos=wx.Point(760, 168), size=wx.Size(85, 16),
              style=0)

        self.TCTotal = wx.TextCtrl(id=wxID_FRAMEPURORDERTCTOTAL,
              name=u'TCTotal', parent=self, pos=wx.Point(848, 112),
              size=wx.Size(88, 24), style=0, value=u'0.0')
        self.TCTotal.SetEditable(False)
        self.TCTotal.SetInsertionPoint(0)
        self.TCTotal.Enable(True)

        self.TCPaid = wx.TextCtrl(id=wxID_FRAMEPURORDERTCPAID, name=u'TCPaid',
              parent=self, pos=wx.Point(848, 136), size=wx.Size(88, 24),
              style=0, value=u'0.0')
        self.TCPaid.SetEditable(False)
        self.TCPaid.Enable(True)

        self.TCUnpaid = wx.TextCtrl(id=wxID_FRAMEPURORDERTCUNPAID,
              name=u'TCUnpaid', parent=self, pos=wx.Point(848, 160),
              size=wx.Size(88, 24), style=wx.TE_READONLY, value=u'0.0')
        self.TCUnpaid.SetForegroundColour(wx.Colour(255, 0, 0))
        self.TCUnpaid.SetEditable(False)
        self.TCUnpaid.Enable(True)
        self.TCUnpaid.SetBackgroundColour(wx.Colour(255, 255, 255))

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.myInit()
        
    def myInit(self):
        import config
        self.SetSize(config.Cfg.getDlgAreaSize())
        self.Move(config.Cfg.getDlgAreaPos())
        
        # 令父窗口随子窗口一同出现
        import kit
        kit.conShow(self)
        
        # supplier
        self.m_supplier = None
        self.TCCustomer.SetFocus()
        
        # Set to Today
        self.dateSO.SetValue(wx.DateTime.Today())
        self.refreshBillId()
        
        # grid
        self.myInitGrid()
        
        #经手人
        self.cbHandler = MyComboBoxDecorator(self.comboBox_staff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(config.Cfg.getCurUser().getValue(CDataStaff.COL_NAME))

        # state matchine
        self.myInitState()
        
        self.myInitPWin()
        
        
        #设置曾经购买的产品列表
        self.lcHistory = MyListCtrlSupplierProRecent(self)
        self.lcHistory.SetSize(wx.Size(400, 350))
        self.lcHistory.Move(wx.Point(760, 200))
        self.lcHistory.Bind(wx.EVT_LEFT_DCLICK, self.OnLcHistoryProLeftDclick)
        
     
    def myInitPWin(self):
        
        self.pWin = DlgPopupSupplier.create(self)

        self.tcPeer = MyPopupTextCtrlDecorator(self.TCCustomer, self.pWin)
           
    def myInitState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW #default state
        self.editedBillId = ''
    
    def isModify(self):
        return self.curState == self.STATE_MODIFY
    
    def myInitGrid(self):
        titles = [(u'编号', 0),
                    (u'产品', 160), 
                    (u'单位', 50), 
                    (u'数量', 70), 
                    (u'单价',70), 
                    (u'小计',100)]
        [self.COL_PROID , self.COL_PRONAME, self.COL_UNIT, self.COL_CNT,
        self.COL_PRICE, self.COL_TOTAL] = [i for i in range(len(titles))]
         
        self.gridSOProList.CreateGrid(0, len(titles))
        for i in range(len(titles)):
            self.gridSOProList.SetColLabelValue(i, titles[i][0])
            self.gridSOProList.SetColSize(i, titles[i][1])
        self.gridSOProList.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        

        #添加右键菜单
        self.menu = wx.Menu()
        
        item = self.menu.Append(-1, u'添加已有商品')
        self.Bind(wx.EVT_MENU, self.OnMenuAdd, item)
        
        item = self.menu.Append(-1, u'添加新商品')
        self.Bind(wx.EVT_MENU, self.OnMenuNewPro, item)
        
        #item = self.menu.Append(-1, u'添加新行')
        #self.Bind(wx.EVT_MENU, self.OnMenuNewRow, item)
        
        item = self.menu.Append(-1, u'删除选中行')
        self.Bind(wx.EVT_MENU, self.OnMenuDelRow, item)

        self.gridSOProList.GetGridWindow().Bind(wx.EVT_RIGHT_UP, self.OnGridRightUp)

    def refreshBillId(self):
        date = self.dateSO.GetValue().Format('%Y%m%d')
        id = CDataPurOrder.newBillId(date)
        self.TSOID.SetLabel(id)
    
    def refreshAmount(self):
        amount = 0
        for i in range(self.gridSOProList.GetNumberRows()):
            amount += float(self.gridSOProList.GetCellValue(i, self.COL_TOTAL))
 
        self.tcYingShou.SetValue(str(amount))
        
    def setSelectObj(self, obj):
        self.m_supplier = obj
     
        name = self.m_supplier.getValue(CDataSupplier.COL_NAME)
        self.tcPeer.ChangeValue(name)
        
        title = u'采购单--%s' %name
        self.SetTitle(title)
        
        # 改变客户时似乎没有必要清空产品列表，有需要的话，手动删
        # DeleteRows(numRows=0)报错
        #self.gridSOProList.DeleteRows(numRows=self.gridSOProList.GetNumberRows()-1)
        #self.gridSOProList.ClearGrid()
        
        # 设置曾经购买的产品列表
        id = obj.getValue(obj.COL_ID)
        self.lcHistory.refresh({'peerId':id})
    
    def loadBill(self, billId):
        sql = "id='%s'" %billId
        objs = CDataPurOrder.fetch(sql)
        if (len(objs) != 1):
            print 'Error incorrect saleId:%s' %billId
            
        billObj = objs[0]
        
        billId = billObj.getValue(billObj.COL_ID)
        peerId = billObj.getValue(billObj.COL_PEERID)
        peerObj = CDataSupplier.getFirstInstance({CDataSupplier.COL_ID:peerId})
        
        self.setSelectObj(peerObj)
        
        self.TSOID.SetLabel(billId)
        

        date = billObj.getValue(billObj.COL_BILLDATE)
        self.dateSO.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0))

        self.tcYingShou.SetValue(str(billObj.getValue(billObj.COL_TOTAL)))
        #COL_PAID,
        #self.tcShiShou.SetValue(str(soObj.getFieldVal(index=CDataSaleOrder.COL_PAID)))
        
        #COL_UNPAID,
      
        self.tcYouHui.SetValue(str(billObj.getValue(billObj.COL_DISCOUNT)))
        
        #COL_HANDLERID,
        #COL_RECOREDERID,
        hId = billObj.getValue(billObj.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        self.cbHandler.SetValue(hObj.getValue(CDataStaff.COL_NAME))
        
        self.tcMemo.SetValue(billObj.getValue(billObj.COL_MEMO))
    
    def loadBillDetail(self, billId):
        '''把销售产品明细显示到grid'''
        self.appendProDetail(CDataPurOrder.getProDetail(billId))
    
    def setEditBill(self, billId):
        '''设置要编辑的订单数据'''
        self.curState = self.STATE_MODIFY
        
        self.editedBillId = billId
        self.loadBill(billId)
        self.loadBillDetail(billId)
            
    def getGridData(self):
        proOnsale = []
        for row in range(self.gridSOProList.GetNumberRows()):
            dataRow = []
            for col in range(self.gridSOProList.GetNumberCols()):
                dataRow.append(self.gridSOProList.GetCellValue(row, col))

            proOnsale.append(dataRow)
            
        return proOnsale
    
    def appendProDetail(self, dataList):
        '''dataList - [[id,name,unit,cnt,price,total],[...]]'''
        print dataList
        grid = self.gridSOProList
        for i in range(len(dataList)):
            row = grid.GetNumberRows()
            grid.AppendRows()
            for col in range(len(dataList[0])):
                grid.SetCellValue(row, col, kit.myStr(dataList[i][col]))
        
        # 添加新数据后，自动重新计算总金额                    
        self.refreshAmount()
    
    def saveBill(self):
        billId = self.TSOID.GetLabel()
        supId = self.m_supplier.getValue(self.m_supplier.COL_ID)
        billDate = self.dateSO.GetValue().Format('%Y-%m-%d')
        
        total = float(self.tcYingShou.GetValue())
        paid = float(self.tcShiShou.GetValue())
        discount = float(self.tcYouHui.GetValue())
        unpaid = total - paid - discount
        
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderId = Cfg.getCurUser().getValue(CDataStaff.COL_ID) 
        
        memo = self.tcMemo.GetValue()
        
        data = {CDataPurOrder.COL_ID:billId, 
                CDataPurOrder.COL_PEERID:supId, 
                CDataPurOrder.COL_BILLDATE:billDate,
                CDataPurOrder.COL_WHID:1, 
                CDataPurOrder.COL_TOTAL:total, 
                CDataPurOrder.COL_PAID:paid,
                CDataPurOrder.COL_DISCOUNT:discount, 
                CDataPurOrder.COL_HANDLERID:handlerId, 
                CDataPurOrder.COL_RECOREDERID:recorderId, 
                CDataPurOrder.COL_MEMO:memo}
                
        obj = CDataPurOrder.factory()
        obj.setMulFieldVal(data)
        return obj.insert()
        
    def saveDetail(self):
        for i in range(self.gridSOProList.GetNumberRows()):
            billId = self.TSOID.GetLabel()
            supId = self.m_supplier.getValue(self.m_supplier.COL_ID)

            proId = self.gridSOProList.GetCellValue(i, 0)
            proName = self.gridSOProList.GetCellValue(i, 1)
            unit = self.gridSOProList.GetCellValue(i, 2)
            num = self.gridSOProList.GetCellValue(i, 3)
            price = self.gridSOProList.GetCellValue(i, 4)
            total = self.gridSOProList.GetCellValue(i, 5)
               
            data = {CDataPurDetail.COL_BILLID:billId, 
                CDataPurDetail.COL_PEERID:supId, 
                CDataPurDetail.COL_PROID:proId,
                CDataPurDetail.COL_PRONAME:proName,
                CDataPurDetail.COL_UNIT:unit,
                CDataPurDetail.COL_NUM:num, 
                CDataPurDetail.COL_PRICE:price, 
                CDataPurDetail.COL_TOTAL:total}
                
            item = CDataPurDetail.factory()
            item.setMulFieldVal(data)
            cnt = item.insert()
            if(cnt <= 0):
                return cnt
        
        return 1    
    
    def disableEdit(self):
        self.TCCustomer.Disable()
        self.gridSOProList.Disable()
        self.tcMemo.Disable()
        self.dateSO.Disable()
        self.comboBox_staff.Disable()
        self.tcYouHui.Disable()
        
        self.btnSave.Disable()
                    
    def OnDateChanged(self, event):
        print 'OnDateChanged'
        if (self.isModify()):
            msg = u'改变日期会导致单据编号发生变化，原来针对此订单的收款等信息将丢失，'\
                    u'是否继续修改？'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return
            
        self.refreshBillId()

    def OnGridRightUp(self, event):
        '''右键菜单弹出'''
        self.gridSOProList.GetGridWindow().PopupMenu(self.menu, event.GetPosition())
    
    def OnMenuAdd(self, event):
        '''右键菜单选中<添加已有商品>'''
        #dlg = DlgSelectPro.create(self)
        #dlg.setViewState(DlgSelectPro.TypePurchase, self.m_supplier)
        dlg = DlgSelectPro.create(self, DlgSelectPro.TypePurchase, self.m_supplier)
        
##        dlg.setShowState(dlgPro.STATE_XS)       
##        self.sendGridToList(dlgPro.listCtrl_proSel,
##                            self.gridSOProList,
##                            self.gridSOProList.GetNumberRows() - 1,
##                            self.gridSOProList.GetNumberCols())
        dlg.appendProDetail(self.getGridData())                    
        if(dlg.ShowModal() == wx.ID_OK):
            numRows=self.gridSOProList.GetNumberRows()
            if(numRows > 0):
                self.gridSOProList.DeleteRows(numRows=numRows)
            # ClearGrid()只会清除数据，不会删除空行
            #self.gridSOProList.ClearGrid()
            self.appendProDetail(dlg.getProSaleList())
            
        
    def OnMenuNewPro(self, event):
        '''右键菜单选中<添加新商品>'''
        event.Skip()
            
    def OnMenuDelRow(self, event):
        '''右键菜单选中<删除选中行>'''
        rows = self.gridSOProList.GetSelectedRows()
        rows.sort(reverse=True)
        for index in rows:
            self.gridSOProList.DeleteRows(index)
        # 避免可能的多个选中导致的循环删除时错删
        #self.gridSOProList.DeleteRows(rows[0])
        self.refreshAmount()
    
    def OnGridSOProListGridCellChange(self, event):
        '''改变<单价><数量>时，重新计算<小计><应收金额>'''
        #print 'OnGridSOProListGridCellChange'
        if (event.GetCol() < self.COL_CNT):
            #cnt\price unchanged
            return
        
        if (event.GetCol() == self.COL_TOTAL):
            msg = u'统计金额不允许修改，请调整单价或设置优惠金额'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
        
        row = event.GetRow()
        total = float(self.gridSOProList.GetCellValue(row, self.COL_CNT)) * \
                    float(self.gridSOProList.GetCellValue(row, self.COL_PRICE))
        self.gridSOProList.SetCellValue(row, self.COL_TOTAL, str(total))
        
        self.refreshAmount()

    def OnGridSOProListGridSelectCell(self, event):
        self.gridSOProList.SelectRow(event.GetRow())
        # 必须保留，以便选中Cell可以进入可编辑状态
        event.Skip()

    def OnGridSOProListGridCellRightClick(self, event):
        self.gridSOProList.SelectRow(event.GetRow())

    def OnLcHistoryProLeftDclick(self, event):
        proId,proName,unit,price = self.lcHistory.getProSaleInfo()
        
        dlg = DlgProGX.create(self)
        dlg.setData(proId=proId, unit=unit, price=price)
        
        if (dlg.ShowModal() == wx.ID_OK):

            unit = dlg.unit
            cnt = dlg.cnt
            price = dlg.price
            total = dlg.cnt*dlg.price
            data = []
            data.append([str(proId), proName, unit, str(cnt), str(price), str(total)])
            self.appendProDetail(data)

    def OnBtnHistoryButton(self, event):
        event.Skip()

    def OnBtnSaveButton(self, event):
        '''保存订单'''
        if (self.m_supplier is None):
            dlg = wx.MessageDialog(self, u'订单未完成：请选择供应商',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        if (self.gridSOProList.GetNumberRows() <= 0):
            dlg = wx.MessageDialog(self, u'订单未完成：未选择产品',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        if(self.isModify()):
            CDataPurOrder.deleteBill(self.editedBillId)
            
        if(self.saveBill() <= 0):
            msg = u'订单保存失败，请查找原因！'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        if(self.saveDetail() <= 0):
            msg = u'产品明细保存失败，请查找原因！'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.disableEdit()
        

    def OnBtnCancelButton(self, event):
        self.Close()

    def OnBtnShowCustomerButton(self, event):
        self.pWin.Show()


